package com.eshop.modules.monitor.service.impl;

import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.connection.DataType;
import java.util.Iterator;
import org.springframework.data.domain.PageImpl;
import java.util.List;
import com.eshop.utils.PageUtil;
import com.eshop.utils.ShopKeyUtils;
import java.util.ArrayList;
import com.eshop.modules.monitor.domain.vo.RedisVo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.eshop.modules.monitor.service.RedisService;

@Service
public class RedisServiceImpl implements RedisService
{
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${loginCode.expiration}")
    private Long expiration;
    
    @Override
    public Page<RedisVo> findByKey(String key, final Pageable pageable) {
        final List<RedisVo> redisVos = new ArrayList<RedisVo>();
        if (!"*".equals(key)) {
            key = "*" + key + "*";
        }
        for (final Object s : this.redisTemplate.keys(key)) {
            if (s.toString().indexOf("role::loadPermissionByUser") == -1 && s.toString().indexOf("user::loadUserByUsername") == -1 && s.toString().indexOf("wechat") == -1 && s.toString().indexOf("wxpay") == -1) {
                if (s.toString().indexOf(ShopKeyUtils.getSiteUrl()) != -1) {
                    continue;
                }
                final DataType dataType = this.redisTemplate.type(s.toString());
                if (!"string".equals(dataType.code())) {
                    continue;
                }
                final RedisVo redisVo = new RedisVo(s.toString(), this.redisTemplate.opsForValue().get(s.toString()).toString());
                redisVos.add(redisVo);
            }
        }
        final Page<RedisVo> page = (Page<RedisVo>)new PageImpl(PageUtil.toPage(pageable.getPageNumber(), pageable.getPageSize(), (List)redisVos), pageable, (long)redisVos.size());
        return page;
    }
    
    @Override
    public void delete(final String key) {
        this.redisTemplate.delete(key);
    }
    
    @Override
    public void flushdb() {
        this.redisTemplate.getConnectionFactory().getConnection().flushDb();
    }
    
    @Override
    public String getCodeVal(final String key) {
        try {
            final String value = this.redisTemplate.opsForValue().get(key).toString();
            return value;
        }
        catch (Exception e) {
            return "";
        }
    }
    
    @Override
    public void saveCode(final String key, final Object val) {
        this.redisTemplate.opsForValue().set(key, val);
        this.redisTemplate.expire(key, (long)this.expiration, TimeUnit.MINUTES);
    }
}
